// pages/questDetail/questDetail.js
const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const user = require('../../utils/user.js');

//获取应用实例
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    questList: '',
    listType: ['单选','多选','自答'],
    isSubmit: false,
    textBop: {
      maxHeight: 200,
      minHeight: 100 
    },
    userQuest: {
      mainId: 0,
      quest: []
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.questId) {
      this.getQuestdDteail(options.questId);
    }
  },
  getQuestdDteail: function (questId) {
    let that = this;
    util.request(api.QuestDetail, {
      id: questId
    }, 'GET').then(res => {
      if (res.errno === 0) {
        that.setData({
          questList: res.data,
        });
      }
      that.handlUserQuest(questId)
    })
  },
  handlUserQuest(questId) {
    let that = this;
    that.data.userQuest.mainId = questId
    that.data.questList.questListVo.forEach(key => {
      let quest = {
        'questId': key.id
      }
      that.data.userQuest.quest.push(quest)
    })
  },
  onChange(e) {
    let that = this;
    let info = e.detail.value
    let a = info.split("_")
    that.data.userQuest.quest[~~a[0]].questId = ~~a[1]
    that.data.userQuest.quest[~~a[0]].answer = a[2]
    console.log(that.data.userQuest)
  },
  checkboxChange(e) {
    let that = this;
    let info = e.detail.value
    let questId = 0
    let index = 0
    let ids = []
    info.forEach(key => {
      let a = key.split("_")
      index = ~~a[0]
      questId = ~~a[1]
      ids.push(~~a[2])
    })
    that.data.userQuest.quest[index].questId = questId
    that.data.userQuest.quest[index].answer = ids
  },
  changeText(e) {
    let that = this
    that.data.userQuest.quest[e.target.dataset.index].questId = e.target.dataset.questid
    that.data.userQuest.quest[e.target.dataset.index].answer = e.detail
  },
  submit() {
    let that = this
    that.setData({
      isSubmit: false,
    })
    let param = that.data.userQuest
    util.request(api.QuestSubmit, { param }, 'POST').then(function (res) {
      if (res.errno === 0) {
        wx.showToast({
          title: '评论成功',
          complete: function () {
            wx.switchTab({
              url: '/pages/quest/quest'
            })
          }
        })
      } else if (res.errno === 505) {
        wx.showToast({
          title: res.errmsg,
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})